package com.shawn.kaoshixingautobot.controller;

import com.microsoft.playwright.options.LoadState;
import com.shawn.kaoshixingautobot.AutoExamStar;
import com.shawn.kaoshixingautobot.util.DialogUtils;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;

public class AutoExamController {

//    @FXML
//    private BorderPane mainPane;

    @FXML
    private TextField examNoField;

    @FXML
    private TextField usernameField;

    @FXML
    private PasswordField passwordField;

    @FXML
    private TextField timesField;

    @FXML
    private Button startButton;

    @FXML
    private ProgressBar progressBar;

    @FXML
    private Label statusLabel;

    private AutoExamStar bot;
    private boolean isRunning = false;

    @FXML
    public void initialize() {
        // 可以设置默认值
//        examNoField.setText("1696307");
//        usernameField.setText("yangshaowei");
//        passwordField.setText("Shawn88~~");
        timesField.setText("5");

        startButton.setOnAction(e -> startExam());
    }

    private void startExam() {
        if (isRunning) {
            showAlert("提示", "正在刷题中，请不要重复点击");
            return;
        }

        // 验证输入
        String examNo = examNoField.getText().trim();
        String username = usernameField.getText().trim();
        String password = passwordField.getText().trim();
        String timesText = timesField.getText().trim();

        if (examNo.isEmpty() || username.isEmpty() || password.isEmpty() || timesText.isEmpty()) {
            showAlert("错误", "请填写所有字段");
            return;
        }

        int times;
        try {
            times = Integer.parseInt(timesText);
            if (times <= 0) {
                showAlert("错误", "刷题次数必须大于0");
                return;
            }
            if (times > 500) {
                showAlert("错误", "刷题次数必须小于500");
                return;
            }
        } catch (NumberFormatException e) {
            showAlert("错误", "请输入有效的数字作为刷题次数");
            return;
        }

        // 禁用输入和按钮，防止重复操作
        disableInput(true);
        progressBar.setProgress(0);
        statusLabel.setText("准备开始刷题...");

        // 创建后台任务
        Task<Void> examTask = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                isRunning = true;
                bot = new AutoExamStar(examNo, username, password, times);

                try {
                    updateStatus("正在登录...");
                    bot.login();
                    updateStatus("登录成功，开始刷题...");

                    // 自定义loopExam方法，支持进度更新
                    for (int i = 0; i < times; i++) {
                        final int current = i + 1;
                        updateStatus("正在进行第 " + current + " 次刷题...");
                        updateProgress(current, times);

                        if (i == 0) {
                            bot.page.navigate(bot.getExamUrl());
                            bot.page.waitForLoadState(LoadState.NETWORKIDLE);
                        }
                        bot.takeExam();

                        // 检查是否被取消
                        if (isCancelled()) {
                            updateStatus("刷题已取消");
                            break;
                        }
                    }

                    if (!isCancelled()) {
                        updateStatus("所有刷题任务已完成！");
                        updateProgress(times, times);
                    }
                } catch (Exception e) {
                    updateStatus("刷题过程中出错: " + e.getMessage());
                    e.printStackTrace();
                } finally {
                    bot.close();
                    isRunning = false;
                    Platform.runLater(() -> disableInput(false));
                }

                return null;
            }

            private void updateStatus(String message) {
                Platform.runLater(() -> statusLabel.setText(message));
            }
        };

        // 绑定进度
        progressBar.progressProperty().bind(examTask.progressProperty());

        // 启动任务
        new Thread(examTask).start();
    }

    private void disableInput(boolean disable) {
        examNoField.setDisable(disable);
        usernameField.setDisable(disable);
        passwordField.setDisable(disable);
        timesField.setDisable(disable);
        startButton.setDisable(disable);
    }

    private void showAlert(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        DialogUtils.setDialogIcon(alert);
        alert.showAndWait();
    }

    // 在类中添加此方法
    public boolean isRunning() {
        return isRunning;
    }

    // 在AutoExamController中添加
    public void stopRunning() {
        // 停止刷题相关的线程或任务
//        if (examThread != null && examThread.isAlive()) {
//            examThread.interrupt();
//        }
        // 释放其他资源（如浏览器驱动、网络连接等）
    }
}